package com.yorge.controller;

import com.yorge.entities.CommonResult;
import com.yorge.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import com.yorge.service.MessageRabbitMQ;
import com.yorge.service.PaymentService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private MessageRabbitMQ messageRabbitMQ;

    @Value("${server.port}")
    private String port;

    @RequestMapping("/getPayment/{id}")
    public CommonResult<Payment> getPayment(@PathVariable Long id) {
        Payment payment = paymentService.getPayment(id);

        CommonResult<Payment> result = CommonResult.success("success:" + port);
        result.setData(payment);

        return result;
    }

    @PostMapping("/addPayment")
    public CommonResult<String> addPayment(@RequestBody Payment payment) {
        int res = paymentService.addPayment(payment);
        if (res > 0) {
            return CommonResult.success("success:" + port);
        } else {
            return CommonResult.error("添加失败");
        }
    }


    @RequestMapping("/discovery")
    public DiscoveryClient discovery() {
        List<String> services = discoveryClient.getServices();
        services.forEach(System.out::println);
        // order服务调用payment时，可以在payment中获取到order服务的相关信息
        List<ServiceInstance> instances = discoveryClient.getInstances(services.get(0));
        instances.forEach(System.out::println);
        return discoveryClient;
    }

    @RequestMapping("/timeOut")
    public String timeOut() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return port;
    }

    @RequestMapping("/get/getPort")
    public String getPort(HttpServletRequest request) {
        String red = request.getParameter("red");
        String header = request.getHeader("X-Request-Red");
        return port + " red:" + red + " header:"+header;
    }


    @RequestMapping("/sendMQ")
    public void sendMQ(String name, String value) {
//        messageRabbitMQ.sendMessage(name, value);
        messageRabbitMQ.sendMessage2(name, value);
    }

}
